/** axios请求初始化封装 **/
import axios from 'axios';
import {getCookie} from "@/utils/common";
import router from '@/router'
import {fail, success} from "@/utils/helper";

// let apiBaseUrl = "http://www.dustar.cn:8080/v1/admin"
// let apiBaseUrl = "http://192.168.2.38:8080/v1/admin";
let apiBaseUrl = "http://127.0.0.1:7001/v1/admin";
// 主路由地址
let instance = axios.create({
    baseURL: apiBaseUrl
});

// 设置拦截器
instance.interceptors.request.use((config) => {
    //在发送请求之前做某事
    if (!config.params) config.params = {};

    if (config.url !== '/login') {
        if (getCookie('authorization')) {
            config.headers = {
                ...config.headers,
                'Authorization': getCookie('authorization')
            }
        }
    }

    return config;
}, function (error) {
    //请求错误时做些事
    return Promise.reject(error);
});


//响应拦截器
instance.interceptors.response.use(function (response) {
    //对响应数据做些事
    return response;
}, function (error) {
   return Promise.reject();
});


// 请求成功的回调
function checkStatus(res) {
    if (res === undefined) return Promise.reject();
    const {code, data} = res.data;
    if (code === 501 && !window.location.href.includes('/login')) router.push("/login");
    if (code === 510) {
        const errList = [...Object.values(data)];
        return fail(errList.length > 0 ? errList.join('\n') : res.message);
    }

    return res.data;
}

// 请求失败的回调
function checkCode(res) {
    // 如果是特殊中断的情况就不做处理
    return {code: 10087, message: "服务器异常"}
}

//模块化导出
export default {
    get(url, params) {
        return instance({
            method: 'get',
            url: url,
            params,
            timeout: 30000,
        }).then(checkStatus).catch(checkCode)
    },
    post(url, params) {
        return instance({
            method: 'post',
            url: url,
            data: params,
            timeout: 30000,
        }).then(checkStatus).catch(checkCode)
    },
    put(url, params) {
        return instance({
            method: 'put',
            url: url,
            data: params,
            timeout: 30000,
        }).then(checkStatus).catch(checkCode);
    },
    delete(url, params) {
        return instance({
            method: 'delete',
            url: url,
            data: params,
            timeout: 30000,
        }).then(checkStatus).catch(checkCode);
    },
    postFile(url, params) {
        return instance({
            method: 'post',
            url: url,
            data: params,
            headers: {'Content-Type': 'multipart/form-data'},
        }).then(checkStatus).catch(checkCode)
    }
}

// 是否销毁拦截器
// 1.给拦截器起个名称 var myInterceptors = instance.interceptors.requesst.use();
// 2.instance.interceptors.request.eject(myInterceptor);
